$(function () {
    var username = getCookie('username')
    if (username) {
        $('.customNav').html(`
        欢迎你，<span style="font-size:14px;color:red;">${username}</span>      

        </a>&nbsp;&nbsp;&nbsp;
        <a title="退出" href="" class="logout">退出</a>
        `)

        $('.logout').click(function () {
            removeCookie('username')
            $('.customNav').html(`
            您还未登录，请
            <a title="登录" href="javascript:;">登录</a>

            <a title="注册" href="register.html">注册</a>
            `)
            gologin()
        })

    } else {
        layer.msg('请先登录！！！', {
            icon: 2,
            time: 1500
        }, function () {
            localStorage.setItem('url', location.href)
            location.href = "login.html";
        })
    }
    gologin()

    //数据
    var data = localStorage.getItem('data')
    if (!data || data === '[]') {
        $('.cartdata').html(`
            <div class="jumbotron">
            <h1>您的购物车还没有道具，赶快去挑选几个吧!</h1>
            <p><a class="btn btn-primary btn-lg" href="paging.html" role="button">去挑选</a></p>
        </div>
        `)
    }
    else {
        // 有数据
        var arr = JSON.parse(data)
        // console.log(arr);
        var ids = arr.map(item => item.goodsid).join(',')
        // console.log(ids);
        $.get('php/shopping.php', { ids }, res => {
            // console.log(res);
            var { meta: { status, msg }, data } = res;
            // console.log(data);
            if (status === 1) {
                var str = '';
                data.forEach(item => {
                    var obj = arr.find(v => v.goodsid == item.id)
                    // console.log(obj.number);
                    str += `
                    <tr >
                    <td>
                        <input type="checkbox" name="selectOne">
                    </td>
                    <td  class="goodsname">
                    <a href="./details.html?id=${item.id}" >
                    ${item.name}
                    </a>
                    </td>
                    <td>
                    <a href="./details.html?id=${item.id}" >
                    <img src="${item.img}">
                    </a>                        
                    </td>
                    <td>${parseInt(item.price * 0.8)}</td>
                    <td data-id="${item.id}" class="bu1">
                        <button class="reduce">-</button>
                        <input type="number" max="9999" min="0" value="${obj.number}" class="tn1">
                        <button class="add">+</button>
                    </td>
                    <td class="subtotal">${parseInt(item.price * 0.8) * obj.number}</td>
                    <td class="bu2">
                        <button class="remove">移出购物车</button>
                    </td>
                </tr>
                    `
                })
                $('.cartdata tbody').html(str)
                // 全选功能
                selectAll()
                // 选择一个的功能
                selectOne()
                // 数量加
                add(arr)
                // 数量减
                reduce(arr)
                // 计算小计
                subtotal()
                // 计算总数量和总价格
                total()
                // 移出购物车
                removeCart(arr)
            }
        }, 'json')
    }
})

function removeCart(arr) {
    $('.remove').click(function () {
        var confirmindex = layer.confirm("你确定要删除吗？", {
            btn: ['残忍删除', '犹豫一会']
        }, () => {
            var goodsid = $(this).parent().siblings('.bu1').attr('data-id')
            var index = arr.findIndex(item => item.goodsid == goodsid)
            arr.splice(index, 1)
            localStorage.setItem('data', JSON.stringify(arr))
            $(this).parent().parent().remove()
            total()
            layer.close(confirmindex)
            layer.msg('删除成功！', {
                icon: 1,
                time: 1500
            })
            if (arr.length === 0) {
                $('.cartdata').html(`
                <div class="jumbotron">
                <h1>您的购物车还没有道具，赶快去挑选几个吧!</h1>
                <p><a class="btn btn-primary btn-lg" href="paging.html" role="button">去挑选</a></p>
            </div>
                `)
            }
        })
    })
}
function total() {
    var num = 0;
    var totalPrice = 0;
    subtotal()
    $('[name="selectOne"]:checked').each((i, v) => {
        num += $(v).parent().siblings('.bu1').find('input').val() - 0
        totalPrice += $(v).parent().siblings('.subtotal').text() - 0
    })
    $('.totalNum').text(num)
    $('.totalPrice').text(totalPrice)
}
function subtotal() {
    $('.tn1').each((i, v) => {
        var num = v.value - 0
        var price = $(v).parent().prev().text() - 0
        if (num < 1) {
            num = 1;
            v.value = num;
        }
        var sub = num * price;
        $(v).parent().next().text(sub)
    })
}
function reduce(arr) {
    $('.reduce').click(function () {
        if ($(this).next().val() <= 2) {

            $(this).css({
                'cursor': 'not-allowed', 'color': '#fff'
            })
        }
        if ($(this).next().val() > 1) {
            var num = $(this).next().val() - 1
            $(this).next().val(num)
            // 获取当前商品的id
            var goodsid = $(this).parent().attr('data-id')
            var obj = arr.find(item => item.goodsid == goodsid)
            obj.number = num;
            localStorage.setItem('data', JSON.stringify(arr))
        }
        subtotal()
        total()
    })
}
function add(arr) {
    $('.add').click(function () {
        var num = $(this).prev().val() - 0 + 1
        $(this).prev().val(num)
        if (num > 1) {
            // $('.cart-number-dec').css('cursor','auto')
            $(this).prev().prev().css({
                'cursor': 'auto', 'color': '#fff'
            })

        }
        // 获取当前商品的id
        var goodsid = $(this).parent().attr('data-id')
        var obj = arr.find(item => item.goodsid == goodsid)
        obj.number = num;
        localStorage.setItem('data', JSON.stringify(arr))
        subtotal()
        total()
    })
}
function selectOne() {
    $('[name="selectOne"]').click(function () {
        var arr = Array.from($('[name="selectOne"]'))
        var bool = arr.every(item => item.checked)
        $('[name="selectAll"]').prop('checked', bool)
        total()
        subtotal()
    })
}

function selectAll() {
    $('[name="selectAll"]').click(function () {
        $('[name="selectOne"]').prop('checked', $(this).prop('checked'))
        $('[name="selectAll"]').prop('checked', $(this).prop('checked'))
        total()
        subtotal()
    })
}
// 登录
function gologin() {
    $('.customNav a:last').click(function () {
        // 点击登录
        // 跳转之前先设置一个本地存储将当前url存起来
        localStorage.setItem('url', location.href)
        // 需要跳转到登录页
        location.href = "login.html";
        // 登录成功后需要跳回来
    })
}